package com.cll.learn.rabbitmq.controller;

import com.cll.learn.rabbitmq.entity.Goods;
import com.cll.learn.rabbitmq.service.GoodsService;
import com.cll.learn.rabbitmq.service.OrderService;
import com.cll.learn.rabbitmq.vo.OrderGoodsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述信息:
 *
 * @author CLL
 * @version 1.0
 * @date 2021/2/3 15:57
 */
@Controller
@RequestMapping(value = "/rabbitmq/goods")
public class GoodsController {

    private static final Logger logger = LoggerFactory.getLogger(GoodsController.class);

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;

    /**
     * 商品列表
     * @param model 数据模型
     * @return  商品列表页面
     */
    @RequestMapping(value = "/list")
    public String list(Model model){
        logger.info("===>>> 访问商品列表页面");
        List<Goods> goodsList = goodsService.listAll();
        logger.info("===>>> 商品列表 = {}", goodsList);
        model.addAttribute("goodsList", goodsList);
        return "goods/list";
    }

    /**
     * 下单操作
     * @param goodsId   商品ID
     * @param model 数据模型
     * @return  待支付页面
     */
    @GetMapping(value = "/{goodsId}/detail")
    public String detail(@PathVariable(value = "goodsId") Integer goodsId, Model model){
        try {
            OrderGoodsVo orderGoodsVo = orderService.generateOrder(goodsId);
            if (null == orderGoodsVo) {
                logger.error("****** 用户下单失败");
                return "error";
            } else {
                model.addAttribute("orderGoodsVo", orderGoodsVo);
                return "goods/detail";
            }
        } catch (Exception e) {
            logger.error("****** 下单抛出异常" + e.getMessage(), e);
            return "error";
        }

    }
}